package com.example.cv.controller;

import com.example.cv.model.Candidate;
import com.example.cv.model.Employee;
import com.example.cv.model.Employer;
import com.example.cv.model.Position;
import com.example.cv.service.CandidateService;
import com.example.cv.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.Get;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周杰
 */
@Controller
public class CandidateController {
    public CandidateService candidateService;

    @Autowired
    public void setCandidateService(CandidateService candidateService) {
        this.candidateService = candidateService;
    }

    public EmployeeService employeeService;

    @Autowired
    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    /**
     * description:求职者登陆的post形式
     * @param candidate,session,model
     * @return java.lang.String
     */
    @PostMapping("/candidateLogin")
    public String candidateLogin(Candidate candidate, HttpSession session, Model model) {
        Candidate c = candidateService.findCandidate(candidate);
        if (c != null) {
            session.setAttribute("candidate", c);
            return "redirect:candidateRecommend?c_id="+c.getC_id();
        } else {
            model.addAttribute("msg","用户名或者密码错误");
            return "login";
        }
    }
    /**
     * description:求职者登退出
     * @param
     * @return java.lang.String
     */
    @GetMapping("/candidateExit")
    public String exitCandidate(HttpSession session) {
        session.removeAttribute("candidate");
        return "redirect:login";
    }
    /**
     * description:求职者注册入口（get）
     * @param
     * @return java.lang.String
     */
    @GetMapping("/candidateRegister")
    public String toRegister() {
        return "candidateRegister";
    }
    /**
     * description:求职者注册提交（post）
     * @param
     * @return java.lang.String
     */
    @PostMapping("/candidateRegister")
    public String toRegister(Candidate candidate,String canIsPublish, HttpSession session,Model model) {
        if(canIsPublish!=null){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String transformDate=simpleDateFormat.format(new Date());
            candidate.setRelease_time(transformDate);
        }
        boolean ret = candidateService.addCandidate(candidate);
        return candidateLogin(candidate,session,model);
    }
    /**
     * description:求职者根据喜好动态查询用人单位
     * @param position
     * @return String
     */
    @PostMapping("/findPositionsByParams")
    public String findPositionsByParams(int c_id,Position position, Model model, @RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
        // 开启分页,参数分别为：当前在第几页，每一页最多有多少条数据
        PageHelper.startPage(pageNum, pageSize);
        List<Position> list=candidateService.findPositionsByParams(position);
        //放入分页对象中,第二个参数表示最多连续显示的页数5
        PageInfo<Position>pageInfo=new PageInfo<Position>(list,5);
        model.addAttribute("positions",list);
        eIsEmployee(c_id,model);
        model.addAttribute("pageInfo",pageInfo);
        return "candidateSearch";
    }

    /**
     * description:判断显示的用人单位是否是候选者
     * @param c_id,model
     * @return java.lang.String
     */
    public void eIsEmployee(int c_id,Model model){
        List<Employee>employees=employeeService.findEmployeesByCId(c_id);
        Map<Integer, Boolean> eIsEmployee = new HashMap<Integer, Boolean>();
        for (int i = 0; i < employees.size(); i++) {
            eIsEmployee.put(employees.get(i).getE_id(),true);
        }
        model.addAttribute("eIsEmployee",eIsEmployee);
    }

    /**
     * description:查询所有用人单位
     * @param session
     * @return String
     */
    @GetMapping("/findAllPositions")
    public String findAllPositions(int c_id, HttpSession session, Model model, @RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
         // 开启分页,参数分别为：当前在第几页，每一页最多有多少条数据
         PageHelper.startPage(pageNum, pageSize);
         List<Position> list=candidateService.findAllPositions();
         //放入分页对象中,第二个参数表示最多连续显示的页数5
         PageInfo<Position>pageInfo=new PageInfo<Position>(list,5);
         session.setAttribute("positions",list);
         eIsEmployee(c_id,model);
         model.addAttribute("pageInfo",pageInfo);
         return "candidateSearch";
    }
    /**
     * description:求职者发布简历
     * @param c_id,model
     * @return java.lang.String
     */
    @GetMapping("/candidatePublish")
    public String candidatePublish(int c_id,Model model_1,Model model_2){
        Candidate c=candidateService.findCandidateById(c_id);
        if(c.getRelease_time()==null){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String transformDate=simpleDateFormat.format(new Date());
            c.setRelease_time(transformDate);
            boolean flag=candidateService.updateCanReleaseTime(c);
            if(flag)  model_1.addAttribute("message","发布成功！");
            else  model_1.addAttribute("message","发布失败！");
        }else{
            model_1.addAttribute("message","您已发布过简历！不能重复发布！");
        }
        updateCanGet(c_id,model_2);
        return "candidateUpdate";
    }
    /**
     * description:求职者撤销发布简历
     * @param c_id,model
     * @return java.lang.String
     */
    @GetMapping("/candidateCancel")
    public String candidateCancel(int c_id,Model model_1,Model model_2){
        Candidate c=candidateService.findCandidateById(c_id);
        if(c.getRelease_time()!=null){
            c.setRelease_time(null);
            boolean flag=candidateService.deleteCanReleaseTime(c);
            if(flag)  model_1.addAttribute("message","撤销成功！");
            else  model_1.addAttribute("message","撤销失败！");
        }else{
            model_1.addAttribute("message","您还未公布简历！");
        }
        updateCanGet(c_id,model_2);
        return "candidateUpdate";
    }

    public void updateCanGet(int c_id,Model model){
        Candidate candidate=candidateService.findCandidateById(c_id);
        model.addAttribute("candidate",candidate);
    }

    /**
     * description:求职者更新个人信息（get）
     * @param
     * @return java.lang.String
     */
    @GetMapping("/updateCandidate")
    public String updateCandidate(int c_id,Model model){
        updateCanGet(c_id,model);
        return "candidateUpdate";
    }

     public void updateCanPost(Candidate candidate,Model model){
        boolean flag=candidateService.updateCandidate(candidate);
        if(flag){
            model.addAttribute("modifyMessage","修改成功！");
        }else{
            model.addAttribute("modifyMessage","修改失败！");
        }
    }

    /**
     * description:求职者更新个人信息（post）
     * @param candidate
     * @return java.lang.String
     */
    @PostMapping("/updateCandidate")
    public String updateCandidate(Candidate candidate,Model model){
        updateCanPost(candidate,model);
        return "candidateUpdate";
    }
    /**
     * description:用人单位查看求职者具体信息
     * @param c_id,model
     * @return java.lang.String
     */
    @GetMapping("/candidateInfo")
    public String candidateInfo(int c_id,Model model){
        Candidate candidate=candidateService.findCandidateById(c_id);
        model.addAttribute("candidate",candidate);
        return "candidateInfo";
    }

    @GetMapping("/candidateRecommend")
    public String candidateRecommend(int c_id,HttpSession session,Model model,@RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "9") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Position>positions=candidateService.findRecommendPositions(c_id);
        //放入分页对象中,第二个参数表示最多连续显示的页数5
        PageInfo<Position> pageInfo=new PageInfo<Position>(positions,5);
        session.setAttribute("recommendPositions",positions);
        eIsEmployee(c_id,model);
        model.addAttribute("pageInfo",pageInfo);
        return "candidateRecommend";
    }

    @GetMapping("/positionInfo")
    public String positionInfo(int p_id,Model model){
        Position position=candidateService.findPositionByPId(p_id);
        model.addAttribute("position",position);
        return "positionInfo";
    }
}
